/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 *
 *PmIndexTabListController
 * 首页tab
 *
 * 修改纪录
 * 2020-05-18 版本：1.0 liwanpeng 创建。
 * @version 版本：1.0
 * @author 作者：liwanpeng
 * 创建日期：2020-05-18
 */

package com.topscomm.mpm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.topscomm.cbo.model.TreeModel;
import com.topscomm.cbo.pojo.CboRoleEntity;
import com.topscomm.cbo.service.impl.CboRoleService;
import com.topscomm.mpm.controller.auto.MpmIndexTabListControllerAuto;
import com.topscomm.mpm.pojo.MpmIndexTabListEntity;
import com.topscomm.mpm.pojo.MpmIndexTabPermissionEntity;
import com.topscomm.mpm.pojo.MpmVueComponentsEntity;
import com.topscomm.mpm.service.impl.MpmIndexTabListService;
import com.topscomm.mpm.service.impl.MpmIndexTabPermissionService;
import com.topscomm.mpm.service.impl.MpmVueComponentsService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.TapSystemConst.TapOperationTypeEnum;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: liwanpeng
 * @date: 2020-05-18
 * @description:首页tabController
 * @modify:
 */
@RestController
@RequestMapping("pm/indexTabList")
public class MpmIndexTabListController extends MpmIndexTabListControllerAuto implements IMpmIndexTabListController {
	@Resource
	private MpmIndexTabListService pmIndexTabListService;
	@Resource
	private CboRoleService cboRoleService;
	@Resource
	private MpmIndexTabPermissionService pmIndexTabPermissionService;
	@Resource
	private MpmVueComponentsService pmVueComponentsService;

	/**
	 * @author: liwanpeng
	 * @date: 2020-05-18
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and name like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_code")) {
			String value = paraMap.get("qry_code").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and code = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_parentid")) {
			String value = paraMap.get("qry_parentid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and parentid = '{0}' ", value);
		}
		return sql.toString();
	}

	@GetMapping(value = "/projectIndexList")
	public ResponseResult<Object> projectIndexList(@RequestParam(required = false) Map<String, Object> paraMap) {
		// 允许权限
		StringBufferProxy sqlPermission = new StringBufferProxy();
		// 禁止权限
		StringBufferProxy sqlPermissionForbidden = new StringBufferProxy();
		sqlPermissionForbidden.appendLineSingle("ISPROHIBIT =1 and ENABLED=1 ");
		List<MpmIndexTabListEntity> tabListForbidden = new ArrayList<>();
		// 超级管理员，不控制权限
		if (this.getUserBean().getUser().getAdminlevel() < 1) {
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "PmProject",
					this.getUserBean());
			if (StringUtil.isEmpty(dataPession))
			{
				// 查询所在部门、此人、此人角色所拥有的tab权限(非禁用)
				// 用户权限
				sqlPermission.appendSingle("enabled =1 and ");

				List<CboRoleEntity> roles = cboRoleService.queryRolesByUserId(this.getUserBean().getUser().getId());
				sqlPermission.appendLineSingle("ISPROHIBIT =0 and ENABLED=1 and ((type =3 and applytocode = '{0}')",
						this.getUserBean().getUser().getCode());
				sqlPermissionForbidden.appendLineSingle("and ((type =3 and applytocode = '{0}')",
						this.getUserBean().getUser().getCode());
				if (roles.size() > 0) {
					sqlPermission.appendLineSingle("or (type = 2 and applytocode in (");
					for (int i = 0; i < roles.size(); i++) {
						CboRoleEntity item = roles.get(i);
						if (i == roles.size() - 1) {
							sqlPermission.appendLineSingle("'{0}'))", item.getCode());
						} else {
							sqlPermission.appendLineSingle("'{0}',", item.getCode());
						}
					}
				}
				// 部门权限
				sqlPermission.appendLineSingle("or ( type = 0 and'" + this.getUserBean().getDept().getCode() + "' like applytocode||'%')");
				sqlPermissionForbidden.appendLineSingle("or ( type = 0 and'" + this.getUserBean().getDept().getCode() + "' like applytocode||'%')");
				//项目角色权限
				if (!StringUtil.isEmpty(ConvertUtil.convertToString(paraMap.get("projectRoleCode")))&&!ConvertUtil.convertToString(paraMap.get("projectRoleCode")).equals("-1")) {
					sqlPermission.appendLineSingle("or (type = 1 and applytocode = {0}))", ConvertUtil.convertToString(paraMap.get("projectRoleCode")));
					sqlPermissionForbidden.appendLineSingle("or (type = 1 and applytocode = {0}))", ConvertUtil.convertToString(paraMap.get("projectRoleCode")));
				}else {
					sqlPermission.appendLineSingle(")");
					sqlPermissionForbidden.appendLineSingle(")", ConvertUtil.convertToString(paraMap.get("projectRoleCode")));
				}

			} else// 使用数据权限
			{
				sqlPermission.appendSingle("{0} ", dataPession);
			}

		}else {
			sqlPermission.appendLineSingle("ISPROHIBIT =0 and ENABLED=1 ");

		}
		// 允许权限
		List<MpmIndexTabPermissionEntity> tabPermissionList = pmIndexTabPermissionService.queryByWhere(sqlPermission.toString());
		// 禁止权限
		tabListForbidden = queryFobbidenTab(sqlPermissionForbidden);

		//允許查看的TAB查詢sql
		StringBufferProxy sqlTabList = new StringBufferProxy();
		List<MpmIndexTabListEntity> tabList = new ArrayList<>();
		// 公开tab
		if (this.getUserBean().getUser().getAdminlevel() <100) {
			sqlTabList.appendLineSingle("ENABLED = 1 and isopen=1 ");
			if (tabPermissionList.size() > 0) {
				sqlTabList.appendLineSingle(" or id in (");
				// 查询有权限的tab
				StringBufferProxy sqlTab = new StringBufferProxy();
				for (int i = 0; i < tabPermissionList.size(); i++) {
					MpmIndexTabPermissionEntity item = tabPermissionList.get(i);
					if (i == tabPermissionList.size() - 1) {
						sqlTabList.appendLineSingle("'{0}')", item.getTabid());

					} else {
						sqlTabList.appendLineSingle("'{0}',", item.getTabid());
					}
				}
			}
		}else {
//			sqlTabList.appendLineSingle("ISPROHIBIT =0 and ENABLED=1 ");

		}
		tabList = pmIndexTabListService.queryByWhere(sqlTabList.toString());

		// 可以查看的TAB
		// 剔除禁止查看的TAB
		// 过滤禁止权限
		Iterator<MpmIndexTabListEntity> iterator = tabList.iterator();
		while (iterator.hasNext()) {
			MpmIndexTabListEntity next = iterator.next();
			for (MpmIndexTabListEntity item : tabListForbidden) {
				if (next.getId() == item.getId()) {
					iterator.remove();
				}
			}
		}
		// 转换成json数组
		JSONArray tabJosonList = JSON.parseArray(JSON.toJSONString(tabList));
		// 查询tab对应的vue组件
		List<MpmVueComponentsEntity> vueComponentList = pmVueComponentsService.queryByWhere("1=1");
		for (int i = 0; i < tabJosonList.size(); i++) {
			List<MpmVueComponentsEntity> vueComponents = new ArrayList<>();
			JSONObject tabListEntity = (JSONObject) tabJosonList.get(i);
			for (int j = 0; j < vueComponentList.size(); j++) {
				if (tabListEntity.getLongValue("id") == vueComponentList.get(j).getTabid()) {
					vueComponents.add(vueComponentList.get(j));
				}
			}
			tabListEntity.put("componentsList", vueComponents);
		}
		List<JSONObject> createTree = createTree(0L, tabJosonList);
		//排序（当前分为2级tab，此处只满足此场景排序需求）
		createTree = createTree.stream().sorted(Comparator.comparing(this::sortedForMoney)).collect(Collectors.toList());
		for(JSONObject item:createTree)
		{
			if (item.get("children")!=null&&item.getJSONArray("children")!=null&&item.getJSONArray("children").size()>0) {
				 List<JSONObject> parseArray = JSONObject.parseArray(item.getJSONArray("children").toJSONString(), JSONObject.class);
				 parseArray=parseArray.stream().sorted(Comparator.comparing(this::sortedForMoney)).collect(Collectors.toList());
				 item.put("children", parseArray);
			}
		}
		return ResponseResult.ok(createTree);
	}
    private double sortedForMoney(JSONObject paramMap) {
        return ConvertUtil.convertToDouble(paramMap.get("sortcode"));
    }
	public List<MpmIndexTabListEntity> queryFobbidenTab(StringBufferProxy sqlPermissionForbidden) {
		List<MpmIndexTabListEntity> tabListForbidden = new ArrayList<>();
		// 禁止权限
		List<MpmIndexTabPermissionEntity> tabPermissionListForbidden = pmIndexTabPermissionService.queryByWhere(sqlPermissionForbidden.toString());
		// 禁止的Tab
		StringBufferProxy sqlTabListforbidden = new StringBufferProxy();
		if (tabPermissionListForbidden.size() > 0) {
			sqlTabListforbidden.appendLineSingle("id in (");
			for (int i = 0; i < tabPermissionListForbidden.size(); i++) {
				MpmIndexTabPermissionEntity item = tabPermissionListForbidden.get(i);
				if (i == tabPermissionListForbidden.size() - 1) {
					sqlTabListforbidden.appendLineSingle("'{0}')", item.getTabid());
				} else {
					sqlTabListforbidden.appendLineSingle("'{0}',", item.getTabid());
				}
			}
			// 禁止查看TAB
			tabListForbidden = pmIndexTabListService.queryByWhere(sqlTabListforbidden.toString());
		}
		return tabListForbidden;
	}
	/**
	 * 递归生成TAB树
	 * @param pid
	 * @param tabJosonList
	 * @return
	 */
	private List<JSONObject> createTree(long pid, JSONArray tabJosonList) {
		List<JSONObject> treeTab = new ArrayList<>();
		for (int i = 0; i < tabJosonList.size(); i++) {
			JSONObject tab = (JSONObject) tabJosonList.get(i);
			if (pid == tab.getLongValue("parentid")) {
				treeTab.add(tab);
				tab.put("children", createTree(tab.getLongValue("id"), tabJosonList));
			}
		}
		return treeTab;
	}

	/**
	 *
	 * @description: 参照查询方法
	 * @param paraMap
	 * @return
	 * @author: liwanpeng
	 * @date: 2020-05-18
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {

		return super.refList(paraMap);
	}

	/**
	 *
	 * @description: 树查询方法
	 * @param paraMap
	 * @return
	 * @author: liwanpeng
	 * @date: 2020-05-18
	 * @modify:
	 */

	@GetMapping(value = "/queryTreeList")
	public ResponseResult<Object> queryTreeList(@RequestParam(required = false) Map<String, Object> paraMap) {
		String sqlWhere = this.spellListSql(paraMap);
		sqlWhere += " order by code asc";
		List<Map<String, Object>> listModule = this.service.queryMapByWhere(sqlWhere);
		List<Map<String, Object>> listNewModule = new ArrayList<Map<String, Object>>();
		listNewModule.addAll(listModule);
		TreeModel treeModel = new TreeModel();
		List<TreeModel> treeList = treeModel.buildTree(listNewModule, true, "首页tab树");
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("dataList", treeList);
		return ResponseResult.ok(dataMap);
	}
}
